package com.lianxian.xindong.home.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hxb.library.base.BaseLazyLoadFragment;
import com.hxb.library.base.MessageEvent;
import com.hxb.library.di.component.AppComponent;
import com.hxb.library.integration.EventBusManager;
import com.hxb.library.utils.HxbUtils;
import com.hxb.library.utils.LogUtils;
import com.lianxian.xindong.commonsdk.core.EventBusHub;
import com.lianxian.xindong.commonsdk.core.RouterHub;
import com.lianxian.xindong.home.R;
import com.lianxian.xindong.home.R2;
import com.lianxian.xindong.home.di.component.DaggerVideoComponent;
import com.lianxian.xindong.home.mvp.contract.VideoContract;
import com.lianxian.xindong.home.mvp.model.entity.VideoUserBean;
import com.lianxian.xindong.home.mvp.presenter.VideoPresenter;
import com.lianxian.xindong.home.mvp.ui.weight.douyin.ListVideoAdapter;
import com.lianxian.xindong.home.mvp.ui.weight.douyin.MyVideoPlayer;
import com.lianxian.xindong.home.mvp.ui.weight.douyin.VideoViewHolder;
import com.paginate.Paginate;

import javax.inject.Inject;

import butterknife.BindView;

import static com.hxb.library.utils.Preconditions.checkNotNull;


/**
 * @作者：hexingbo
 * @时间：07/02/2023
 * @描述：自拍（视频播放页面）
 */
public class VideoFragment extends BaseLazyLoadFragment<VideoPresenter> implements VideoContract.View {

    @Inject
    LinearLayoutManager mLayoutManager;
    @Inject
    ListVideoAdapter videoAdapter;

    @BindView(R2.id.rv_page2)
    RecyclerView rvPage2;
    @BindView(R2.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;

    private Paginate mPaginate;
    private boolean isLoadingMore;
    private PagerSnapHelper snapHelper;

    private int currentPosition;

    public static VideoFragment newInstance() {
        VideoFragment fragment = new VideoFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerVideoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_video, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(rvPage2);
        rvPage2.setLayoutManager(mLayoutManager);
        rvPage2.setAdapter(videoAdapter);
        initPaginate();
        addListener();
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        mRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        HxbUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        HxbUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    protected void lazyLoadData() {
        LogUtils.debugInfo("加载了吗");
        mPresenter.requestDatas(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        MyVideoPlayer.releaseAllVideos();
    }

    @Override
    protected void onMessageEvent(MessageEvent message) {
        super.onMessageEvent(message);
        if (message.getType().equals(EventBusHub.EVENT_SELFIEFRAGMENT_VIDEOPLAYPAUSE)) {
            videoAdapter.onPausePlay();
        } else if (message.getType().equals(EventBusHub.EVENT_SELFIEFRAGMENT_VIDEOPLAYSTART)) {
            videoAdapter.onStartPlay();
        }
    }

    @Override
    public void initPaginate() {
        if (mPaginate == null) {
            Paginate.Callbacks callbacks = new Paginate.Callbacks() {
                @Override
                public void onLoadMore() {
                    //在需要加载数据的时候会调用onLoadMore()方法
                    mPresenter.requestDatas(false);
                }

                @Override
                public boolean isLoading() {
                    //则用于判断是否正在进行加载，若正处于加载状态中则返回true，否则返回false
                    return isLoadingMore;
                }

                @Override
                public boolean hasLoadedAllItems() {
                    //则用于判断是否还有需要加载的数据，若已经加载了全部的数据则返回true，否则返回false。
                    return mPresenter.hasLoadedAllItems();
                }
            };

            mPaginate = Paginate.with(rvPage2, callbacks)
                    .setLoadingTriggerThreshold(0)
                    .build();
            mPaginate.setHasMoreDataToLoad(false);
        }
    }

    @Override
    public void endLoadMore() {
        isLoadingMore = false;
    }

    @Override
    public void clickHead(VideoUserBean position) {
        ARouter.getInstance()
                .build(RouterHub.ME_FRIENDDETAILACTIVITY)
                .navigation(getContext());
    }

    @Override
    public void clickCare(VideoUserBean bean) {

    }

    @Override
    public void clickZan(VideoUserBean bean) {

    }

    @Override
    public void clickMesDrop(VideoUserBean bean) {

    }

    @Override
    public void clickMsgHi(VideoUserBean bean) {

    }

    @Override
    public void clickLiWu(VideoUserBean bean) {

    }

    private void addListener() {
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.requestDatas(true);
            }
        });
        rvPage2.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE://停止滚动
                        View view = snapHelper.findSnapView(mLayoutManager);
                        //当前固定后的item position
                        int position = recyclerView.getChildAdapterPosition(view);
                        if (currentPosition != position) {
                            //如果当前position 和 上一次固定后的position 相同, 说明是同一个, 只不过滑动了一点点, 然后又释放了
                            MyVideoPlayer.releaseAllVideos();
                            RecyclerView.ViewHolder viewHolder = recyclerView.getChildViewHolder(view);
                            if (viewHolder != null && viewHolder instanceof VideoViewHolder) {
                                ((VideoViewHolder) viewHolder).mp_video.startVideo();
                                videoAdapter.setVideoPlayer(((VideoViewHolder) viewHolder).mp_video);
                            }
                        }
                        currentPosition = position;
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://拖动
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://惯性滑动
                        break;
                }

            }
        });
    }

}
